var dbutil = require('../utils/dbWrapperUtil'),
    _ = require('underscore');

var JOB_FILTER_TABLE = 'job_filter';
var STATUS_SUCCESS = 'success';
var STATUS_FAILED = 'failed';

exports.subscribeTopic = function(user_id, filter, callback) {
    if(filter && _.isNumber(user_id)){
        var filter_str = JSON.stringify(filter);
        var filterData = {user_id: user_id, filter: filter_str};
        dbutil.dbtemplate(function(dbwrapper, dbcloseCallback){
            dbwrapper.insert(JOB_FILTER_TABLE, filterData, function(err){
                dbcloseCallback();
                if(!err) {
                    callback(null, {status: STATUS_SUCCESS, statusDesc: "subscribe success"}, filter);
                } else {
                    callback(err, {status: STATUS_FAILED, statusDesc: "subscribe failed"}, filter)
                }
            });
        });
    } else {
        callback(null, {status: STATUS_FAILED, statusDesc: "subscribe failed"}, filter)
    }
};

exports.getSubTopic = function(user_id, callback) {
    dbutil.dbtemplate(function(dbwrapper, dbcloseCallback){
        var sql = 'select * from ' + JOB_FILTER_TABLE + ' where user_id=?';
        dbwrapper.fetchRow(sql, [user_id], function(err, result){
            dbcloseCallback();
            if(!err) {
                callback(null, {status: STATUS_SUCCESS, statusDesc: "get topic success"}, result);
            } else {
                callback(err, {status: STATUS_FAILED, statusDesc: "get topic failed"}, null);
            }
        });
    });
};